/*
* Filename:network.c
* Summary:implement the netwrok related functions	
*
* Author:LiuHui
* Version:0.0
* Finished time:
*/
#include "head.h"
#include "network.h"
#include "config.h"
#include "ipmsg.h"
//the global variables
int globalfd;
GIOChannel *io_channel;

/*
* Function:
* Summary:
*
* Argument:
* 1th argument --
* 2th argument --
*
* Return:
*  
*/
int SocketInit()
{
	int sockfd;
	struct sockaddr_in localaddr;
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	memset((char *)(&localaddr), 0, sizeof(localaddr));
	int optval = 1;
	localaddr.sin_family = AF_INET;
	localaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	localaddr.sin_port = htons(IPMSG_PORT);
	int i = bind(sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));
#ifdef _DEBUG
	if ( i < 0 )
	{
		perror("Bind Error\n");
	} else
	{
		printf("Bind Succeed\n");
	}
#endif
	//set socket attrubute to support broadcast
	int j = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval));    
#ifdef _DEBUG
	if ( j < 0 )
	{
		perror("Setsockopt Error\n");
	} else
	{
		printf("Setsockopt Succeed\n");
	}
#endif
	return sockfd;
}

void SayHello()
{
	char buf[MAX_MESSAGE] = {'\0'};
	memset(buf, '\0', MAX_MESSAGE);
	int size = AssembleMessage(buf, IPMSG_BR_ENTRY, "", 0);
	struct sockaddr_in bro_addr;
	bzero(&bro_addr, sizeof(bro_addr));
	bro_addr.sin_family = AF_INET;
	bro_addr.sin_port = htons(IPMSG_PORT);
	bro_addr.sin_addr.s_addr = inet_addr("255.255.255.255");
	int err = sendto(globalfd, buf, size + 1, 0, 
					 (struct sockaddr *)&bro_addr, sizeof(struct sockaddr_in));
#ifdef _DEBUG
	if ( err < 0 )
	{
		perror("Error in say hello\n");
	} else
	{
		printf("SayHello Succeed\n");
	}
#endif
}
